package com.patrol.patrol.ui;

import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.gson.Gson;
import com.google.zxing.common.StringUtils;
import com.patrol.patrol.MyApplication;
import com.patrol.patrol.R;
import com.patrol.patrol.data.EventImgModel;
import com.patrol.patrol.data.EventImgModelDTO;
import com.patrol.patrol.data.EventModel;
import com.patrol.patrol.data.EventModelDTO;
import com.patrol.patrol.utils.DateUtils;
import com.patrol.patrol.utils.FileUtils;
import com.patrol.patrol.utils.LogUtils;
import com.patrol.patrol.utils.PickerDialog;
import com.patrol.patrol.utils.ToastUtils;

import org.jaaksi.pickerview.picker.BasePicker;
import org.jaaksi.pickerview.picker.TimePicker;
import org.jaaksi.pickerview.widget.PickerView;
import org.json.JSONArray;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = "/app/UpdateActivity")
public class UpdateActivity extends BaseActivity implements TimePicker.OnTimeSelectListener {


    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.tv_title)
    TextView tvTitle;

    private TimePicker mTimePicker;
    public static final DateFormat sSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private int mCurrYear;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_to_update);
        ButterKnife.bind(this);
tvTitle.setText("上传");

        tvStartTime.setText(sSimpleDateFormat.format(new Date()));
        tvEndTime.setText(sSimpleDateFormat.format(new Date()));
        initPicker();

    }

    private void initPicker() {
        int type = 0;
        type = TimePicker.TYPE_YEAR | TimePicker.TYPE_MONTH | TimePicker.TYPE_DAY;
        mTimePicker = new TimePicker.Builder(mContext, type, this)
                // 设置时间区间
                .setRangDate(1577891229000L, 1893563460000L)
                //.setContainsStarDate(true)
                .setTimeMinuteOffset(10)
                //.setSelectedDate(1526449500000L).setTimeMinuteOffset(10)
                // 设置选中时间
                .setSelectedDate(System.currentTimeMillis())
                // 设置pickerview样式
                .setInterceptor(new BasePicker.Interceptor() {
                    @Override
                    public void intercept(PickerView pickerView, LinearLayout.LayoutParams params) {
                        pickerView.setVisibleItemCount(3);
                        // 将年月设置为循环的
                        int type = (int) pickerView.getTag();
                        //if (type == TimePicker.TYPE_YEAR || type == TimePicker.TYPE_MONTH) {
                        //  pickerView.setIsCirculation(true);
                        //}
                    }
                })
                // 设置 Formatter
                .setFormatter(new TimePicker.DefaultFormatter() {
                    // 自定义Formatter显示去年，今年，明年
                    @Override
                    public CharSequence format(TimePicker picker, int type, int position, long num) {
                        if (type == TimePicker.TYPE_YEAR) {
                            long offset = num - mCurrYear;
                            if (offset == -1) return "去年";
                            if (offset == 0) return "今年";
                            if (offset == 1) return "明年";
                            return num + "年";
                        } else if (type == TimePicker.TYPE_MONTH) {
                            return String.format("%d月", num);
                        }

                        return super.format(picker, type, position, num);
                    }
                }).create();
        PickerDialog dialog = (PickerDialog) mTimePicker.dialog();
        dialog.getTitleView().setText("请选择时间");
    }

    boolean isStart = true;
    @RequiresApi(api = Build.VERSION_CODES.N)
    @OnClick({R.id.tv_start_time, R.id.tv_end_time, R.id.tv_update})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_start_time:
                try {
                    // 设置选中时间
                    Date date = sSimpleDateFormat.parse(tvStartTime.getText().toString());
                    mTimePicker.setSelectedDate(date.getTime());
                } catch (ParseException e) {
                    // 如果没有设置选中时间，则取起始时间
                    e.printStackTrace();
                    //mTimePicker.setSelectedDate(mLoveTimes);
                }
                mTimePicker.show();
                isStart = true;
                break;
            case R.id.tv_end_time:
                try {
                    // 设置选中时间
                    Date date = sSimpleDateFormat.parse(tvEndTime.getText().toString());
                    mTimePicker.setSelectedDate(date.getTime());
                } catch (ParseException e) {
                    // 如果没有设置选中时间，则取起始时间
                    e.printStackTrace();
                    //mTimePicker.setSelectedDate(mLoveTimes);
                }
                mTimePicker.show();
                isStart = false;
                break;
            case R.id.tv_update:
                String start = DateUtils.date2TimeStamp(tvStartTime.getText().toString() + " 00:00:00","yyyy-MM-dd HH:mm:ss");
                String end = DateUtils.date2TimeStamp(tvEndTime.getText().toString() + " 23:59:59","yyyy-MM-dd HH:mm:ss");
                List<EventModel> list = MyApplication.dbProxy.queryListBySql(EventModel.class, "select * from event_model where time between " + start + " and " + end);
                List<EventModelDTO> dtoList = new ArrayList<>();
                if(null != list && list.size()>0){

                    list.forEach(model->{
                        EventModelDTO modelDTO = new EventModelDTO();
                        modelDTO.setName(model.getEtName())
                                .setCardNo(model.getEtNum())
                                .setRemark(model.getEtRemark())
//                                .setOrgId(model.getEtSchool())
                                .setType(model.getSpSex())
                                .setCreateTime(DateUtils.timeStamp2Date(model.getTime() + "","yyyy-MM-dd HH:mm:ss"));
                        List<EventImgModel> imgModelList = MyApplication.dbProxy.queryListBySql(EventImgModel.class,"select * from event_img_model where event_id = " + model.getPrimaryKey());
                        List<EventImgModelDTO> imgDTOList = new ArrayList<>();
                        if(null != imgModelList && imgModelList.size()>0){
                            imgModelList.forEach(img->{
                                EventImgModelDTO imgModelDTO = new EventImgModelDTO();
                                imgModelDTO.setSavePath(img.getImageUrl());
                                imgModelDTO.setFileName(img.getImageUrl().substring(img.getImageUrl().lastIndexOf("/")));
                                imgDTOList.add(imgModelDTO);
                            });
                        }
                        modelDTO.setResource(imgDTOList);
                        dtoList.add(modelDTO);
                    });
                }
                Gson gson = new Gson();
                String json = gson.toJson(dtoList);
                FileUtils.writeStringToFile(json,"/mnt/sdcard/index.json");
                ToastUtils.showToast("导出成功");
                break;
        }
    }

    @Override
    public void onTimeSelect(TimePicker picker, Date date) {
        if (isStart){
            tvStartTime.setText(sSimpleDateFormat.format(date));
        }else {
            tvEndTime.setText(sSimpleDateFormat.format(date));
        }
    }
}
